package com.yupi.yuojcodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.io.IOException;

public class DockerTest {
    public static void main(String[] args) throws InterruptedException, IOException {

        // 配置 Docker 客户端
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("unix:///var/run/docker.sock") // 使用 Unix 套接字
                .build();

        // 创建 Docker 客户端
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

        try {
            // 拉取 JDK 8 镜像
//            System.out.println("正在拉取 JDK 8 镜像...");
//            dockerClient.pullImageCmd("openjdk:8-jdk")
//                    .exec(new PullImageResultCallback())
//                    .awaitCompletion();
            System.out.println("JDK 8 镜像拉取完成！");

            // 创建容器
            System.out.println("正在创建容器...");
            CreateContainerResponse container = dockerClient.createContainerCmd("openjdk:8-jdk")
                    .withCmd("sh", "-c", "java -version && tail -f /dev/null") // 执行命令后保持运行
                    .exec();
            System.out.println("容器创建成功，ID: " + container.getId());

            // 启动容器
            System.out.println("正在启动容器...");
            dockerClient.startContainerCmd(container.getId()).exec();
            System.out.println("容器启动成功！");

            // 查看容器日志
            System.out.println("容器日志:");
            dockerClient.logContainerCmd(container.getId())
                    .withStdOut(true)
                    .withStdErr(true)
                    .withFollowStream(true)
                    .exec(new LogContainerResultCallback() {
                        @Override
                        public void onNext(Frame item) {
                            System.out.println(new String(item.getPayload()));
                        }
                    })
                    .awaitCompletion();
        } catch (Exception e) {
            System.err.println("操作失败: " + e.getMessage());
        } finally {
            // 关闭 Docker 客户端
            dockerClient.close();
        }

    }
}
